<template>
  <div p-5>
    <DynamicTable
      ref="dynamicTableRef"
      bordered
      :data-request="loadData"
      :columns="columns"
      row-key="heroid"
      :scroll="{
        y: 'calc(100vh - 400px)',
      }"
    >
      <template #toolbar>
        <a-button type="primary" @click="createTask"> 新建任务 </a-button>
      </template>
    </DynamicTable>
  </div>
</template>

<script lang="ts" setup>
  import { useRouter } from 'vue-router';
  import { Taskcolumns, type TableColumnItem } from './columns';
  import { useTable } from '@/components/core/dynamic-table';

  import { deleteTask, getTaskList } from '@/api/supervision/task-management';
  import { Modal } from 'ant-design-vue';
  import { getApproveRecord } from '@/api/supervision/taskApproval';
  import { getAreaList } from '@/api/administrativePenalty/case-management';
  import { getSelectAreaList } from '@/api/administrativePenalty/case-management';
  import { onMounted, ref } from 'vue';

  import { downloadFile } from '@/api/account';
  const tableHeight = 'calc(100vh - 500px)';
  const router = useRouter();
  const [DynamicTable, dynamicTableInstance] = useTable();

  //区域相关
  const countyOptions = ref([] as any);
  const townOptions = ref([] as any);
  const areaFieldNames = {
    label: 'name',
    value: 'id',
  };

  const loadData = async (params): Promise<API.TableListResult> => {
    if (params.dataTime) {
      params.startTime = params.dataTime[0];
      params.endTime = params.dataTime[1];
      delete params.dataTime;
    }

    const data = await getTaskList(params);
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          list: data,
          ...params,
        });
      }, 500);
    });
  };

  //新建任务
  const createTask = () => {
    router.push({ path: '/supervision/create-task' });
  };

  const delRowConfirm = async (id: string) => {
    if (Array.isArray(id)) {
      Modal.confirm({
        title: '确定要删除所选的用户吗?',
        icon: '',
        centered: true,
        onOk: async () => {
          await deleteTask(id);
        },
      });
    } else {
      await deleteTask(id).finally(dynamicTableInstance?.reload);
    }
  };

  const downFile = (url, name) => {
    var fileUrl = url; // 文件的URL
    var fileName = name; // 新的文件名

    var xhr = new XMLHttpRequest();
    xhr.open('GET', fileUrl, true);
    xhr.responseType = 'blob';

    xhr.onload = function () {
      if (xhr.status === 200) {
        var blob = xhr.response;
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
      }
    };

    xhr.send();
  };

  const handleDown = (val) => {
    const nameFix = val.split('.')[val.split('.').length - 1];
    let checkItem = '检查结果表';
    downFile(
      `${import.meta.env.VITE_BASE_API}/manage/upload/downloadFile?fileUrl=${val}`,
      `${checkItem}.${nameFix}`,
    );
  };

  const columns: TableColumnItem[] = [
    ...Taskcolumns,
    {
      title: '机构名称',
      dataIndex: 'countyCode',
      hideInTable: true,
      formItemProps: {
        component: 'Select',
        colProps: {
          style: 'width: 240px',
        },
        componentProps: ({ formModel, formInstance }) => {
          return {
            placeholder: '请选择区域',
            options: countyOptions.value,
            fieldNames: areaFieldNames,
            autocomplete: 'off',
            disabledLabelWidth: true,
            onChange: (e: any) => {
              countyOptions.value.map((item) => {
                if (item.id == e) {
                  townOptions.value = item.children;
                }
              });
              formModel.townCode = undefined;
            },
          };
        },
      },
    },
    {
      dataIndex: 'townCode',
      hideInTable: true,
      formItemProps: {
        component: 'Select',
        colProps: {
          style: 'width: 178px',
        },
        componentProps: () => {
          return {
            placeholder: '请选择街道',
            options: townOptions.value,
            fieldNames: areaFieldNames,
            // changeOnSelect: true,
          };
        },
      },
    },
    {
      title: '操作',
      align: 'left',
      fixed: 'right',
      width: 210,
      dataIndex: 'ACTION',
      actions: ({ record }) => [
        {
          label: '查看',
          onClick: () => {
            if (
              record.taskStatus == 6 ||
              (record.taskStatus == 5 &&
                record.processType &&
                record.processType.split(',').includes('2'))
            ) {
              // 待回证 ||  已结束-责令改正
              router.push({
                path: '/supervision/taskApproval',
                query: {
                  id: record.id,
                  progressId: record.progressId,
                  isCheck: '1',
                  handleShowFlag: record.handleShowFlag,
                  taskStatus: record.taskStatus,
                },
              });
            } else if (record.taskStatus == 4) {
              // 待处理 判断有没有审批记录
              getApproveRecord(record.id).then((res) => {
                if (res.length) {
                  router.push({
                    path: '/supervision/taskApproval',
                    query: {
                      id: record.id,
                      progressId: record.progressId,
                      isCheck: '1',
                      handleShowFlag: record.handleShowFlag,
                      taskStatus: record.taskStatus,
                    },
                  });
                } else {
                  router.push({
                    path: '/supervision/task-view',
                    query: { id: record.id, handleShowFlag: record.handleShowFlag },
                  });
                }
              });
            } else {
              router.push({
                path: '/supervision/task-view',
                query: { id: record.id, handleShowFlag: record.handleShowFlag },
              });
            }
          },
        },
        {
          label: '编辑',
          ifShow: record.editShowFlag == 1,
          onClick: () =>
            router.push({
              path: '/supervision/create-task',
              query: { id: record.id },
            }),
        },
        {
          label: '删除',
          ifShow: record.deleteShowFlag == 1,
          popConfirm: {
            title: '你确定要删除吗？',
            onConfirm: () => delRowConfirm(record.id),
          },
        },
        {
          label: '处理',
          ifShow: record.handleShowFlag == 1,
          onClick: () => {
            if (record.taskStatus == 6) {
              // 待回证
              router.push({
                path: '/supervision/taskApproval',
                query: { id: record.id, progressId: record.progressId, isCheck: '3' },
              });
            } else {
              router.push({
                path: '/supervision/handleTask',
                query: { id: record.id },
              });
            }
          },
        },
        {
          label: '下载检查结果表',
          ifShow: record.resultFileUrl != '',
          onClick: () => handleDown(record.resultFileUrl),
        },
      ],
    },
  ];
  onMounted(async () => {
    const res_area = await getSelectAreaList();
    if (res_area.code === 0) {
      countyOptions.value = res_area.data[0].children;
    }
  });
</script>

<style lang="less" scoped></style>
